import type { BaseSystem } from '../base';

export class Loop {
  /** 多少毫秒执行一次 */
  private step = 100;
  private isRunning = false;
  /** 进行了多少毫秒 */
  private time = 0;
  private lastTime = performance.now();
  private systems: BaseSystem[] = [];

  constructor(systems: BaseSystem[]) {
    this.systems = systems;
  }

  private tick() {
    if (!this.isRunning) return;
    const now = performance.now();
    const dt = now - this.lastTime;
    this.time += dt;

    while (this.time >= this.step) {
      /** 将毫秒转换为秒 */
      const secondsDt = this.step / 1000;
      this.systems.forEach((s) => s.update?.(secondsDt));
      this.time -= this.step;
    }

    this.lastTime = now;

    requestAnimationFrame(() => this.tick());
  }

  public start() {
    if (this.isRunning) return;
    this.isRunning = true;
    this.lastTime = performance.now();
    this.tick();
  }

  public stop() {
    if (!this.isRunning) return;
    this.isRunning = false;
  }
}
